<template>
    <el-form class="login-form" :model="form" :rules="rules" ref="loginForm" label-width="70px" label-position="right"
        status-icon>
        <h1 class="headerline">后台管理系统</h1>
        <el-form-item label="用户名" prop="userName">
            <el-input v-model.trim="form.userName" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model.trim="form.password" type="password" placeholder="密码" clearable show-password></el-input>
        </el-form-item>
        <el-form-item label-position="right">
            <el-button type="primary" @click="onLogin" plain>登录</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
// 导入 Vue 的响应式 API
import { onMounted, reactive, ref } from "vue";
// 导入登录 API
import { login } from "@/apis/common";
import { ElMessage } from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();

const loginForm = ref();
// 创建一个响应式对象来存储用户名和密码
const form = reactive({
    userName: "",
    password: ""
});

const rules = reactive({
    userName: { required: true, message: "请输入用户名" },
    password: [
        { required: true, message: "请输入密码" },
        { min: 6, message: "密码长度不能少于6位" }
    ],
});
// 定义登录方法，异步处理登录请求
const onLogin = async () => {
    // 检查登录表单是否存在，若不存在则直接返回
    if (!loginForm.value) return;
    loginForm.value.validate(async (valid: boolean) => {
        // 若表单验证通过
        if (valid) {
           const res = await login(form);
           // 登录成功后跳转到后台管理系统主页
                      if(res.data.code === 0){
                       localStorage.setItem('gx-token', res.data.data);
                       ElMessage.success(res.data.msg);
                       router.replace('/control')
                      }else{
                       ElMessage.error(res.data.msg);
                      }
           // 根据返回的code判断请求结果，若成功则将token存入localStorage，显示成功消息并跳转到控制页面；若失败则显示错误消息。
        }
    });
}

onMounted(() =>{
    // 监听回车键按下，触发登录事件
    document.onkeydown = (e: any) => {
        if (e.keyCode === 13) {
            onLogin();
        }
    }
})
</script>
<style>
.login-form {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 300px;
    background-color: white;
    padding: 20px;
    box-shadow: var(--el-box-shadow-dark);
    border-radius: 4px;
    background-image: url(../assets/img/6EF6BBF5A4EC9B58B3754A1E7836C689.gif);
    background-size: cover;
}

.headerline {
    font-size: 20px;
    text-align: center;
    margin-bottom: 20px;
}
</style>